package com.link.play.fit.ai.ui.view

import android.content.Context
import android.os.Looper
import android.util.AttributeSet
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.TranslateAnimation
import android.widget.Toast
import androidx.appcompat.widget.AppCompatTextView
import com.link.play.fit.ai.R
import com.link.play.fit.ai.ext.d

class AutoScrollTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    // 配置参数
    private var textList = emptyList<String>()    // 文本列表
    private var currentIndex = 0                 // 当前显示索引
    private var delayMillis = 2000L              // 每条展示时长（2秒）
    private var animDuration = 500L              // 动画时长（毫秒）
    private val handler = android.os.Handler(Looper.getMainLooper())
    private var isRunning = false

    // 初始化属性（可从XML配置）
    init {
        context.obtainStyledAttributes(attrs, R.styleable.AutoScrollTextView).apply {
            delayMillis = getInt(R.styleable.AutoScrollTextView_holdDuration, 2) * 1000L
            animDuration = getInt(R.styleable.AutoScrollTextView_animDuration, 500).toLong()
            recycle()
        }
    }

    // 设置数据源
    fun setData(list: List<String>) {
        textList = list
        if (list.isNotEmpty()) {
            text = list[0]
        }
    }

    // 启动自动滚动
    fun startAutoScroll() {
        if (textList.size <= 1 || isRunning) return
        isRunning = true
        scheduleNext()
    }

    // 停止滚动
    fun stopAutoScroll() {
        handler.removeCallbacksAndMessages(null)
        isRunning = false
    }

    // 调度下一条
    private fun scheduleNext() {
        handler.postDelayed({
            playSwitchAnimation()
        }, delayMillis)
    }

    // 播放切换动画
    private fun playSwitchAnimation() {
            kotlin.runCatching {
                val nextIndex = (currentIndex + 1) % textList.size
                // 创建向上退出动画
                val exitAnim = TranslateAnimation(
                    0f, 0f,
                    0f, -height.toFloat()
                ).apply {
                    duration = animDuration
                    setAnimationListener(object : Animation.AnimationListener {
                        override fun onAnimationStart(animation: Animation?) {}
                        override fun onAnimationEnd(animation: Animation?) {
                            // 动画结束后更新内容
                            if (textList.isEmpty()) {
                                return
                            }
                            if (nextIndex >= textList.size) {
                                text = textList[0]
                                currentIndex = 0
                            } else {
                                text = textList[nextIndex]
                                currentIndex = nextIndex
                            }
                            // 重置位置并启动进入动画
                            startEnterAnimation()
                        }

                        override fun onAnimationRepeat(animation: Animation?) {}
                    })
                }
                val enterAlphaAnim = AlphaAnimation(1f, 0f).apply { duration = animDuration }
                val enterAnimSet = AnimationSet(true).apply {
                    addAnimation(exitAnim)
                    addAnimation(enterAlphaAnim)
                }
                startAnimation(enterAnimSet)
            }

    }


    // 启动进入动画（从底部滑入）
    private fun startEnterAnimation() {
        val enterAnim = TranslateAnimation(
            0f, 0f,
            height.toFloat(), 0f
        ).apply {
            duration = animDuration
            setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation?) {}
                override fun onAnimationEnd(animation: Animation?) {
                    // 继续调度下一条
                    scheduleNext()
                }

                override fun onAnimationRepeat(animation: Animation?) {}
            })
        }

        val enterAlphaAnim = AlphaAnimation(0f, 1f).apply { duration = animDuration }
        val enterAnimSet = AnimationSet(true).apply {
            addAnimation(enterAnim)
            addAnimation(enterAlphaAnim)
        }
        startAnimation(enterAnimSet)
    }

    // 生命周期管理
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopAutoScroll()
    }
}
